package com.tanhua.server.interceptor;

import com.tanhua.common.utils.Cache;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@Component
public class RedisCacheInterceptor implements HandlerInterceptor {
    @Value("${tanhua.cache.enable}")
    private Boolean enable;
    @Autowired
    private RedisTemplate<String, String> restTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        //检验是否开启redis缓存
        if (!enable) {
            return true;
        }
        //检验是否访问Cotroller的动态资源
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //检验是否以get的方式访问
        if (!((HandlerMethod) handler).hasMethodAnnotation(GetMapping.class)) {
            return true;
        }
        //检验是否有被Cache标记
        if (((HandlerMethod) handler).hasMethodAnnotation(Cache.class)) {
            return true;
        }
        //缓存命中
        String redisKey = createRedisKey(request);
        String reponseData = restTemplate.opsForValue().get(redisKey);
        if (StringUtils.isEmpty(reponseData)) {
            //缓存未命中
            return true;
        }
        //设置响应的格式
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        //从redis中拿来的数据响应给前端
        response.getWriter().write(reponseData);
        return false;

    }

    /**
     * 生成redis中的key，规则：SERVER_CACHE_DATA_MD5(url + param + token)
     *
     * @param request
     * @return
     */
    public static String createRedisKey(HttpServletRequest request) {
        String url = request.getRequestURI();
        Map<String, String[]> param = request.getParameterMap();
        String token = request.getHeader("Authorization");
        String keySuffix = DigestUtils.md5Hex(url + "_" + param + "_" + token);
        return "SERVER_CACHE_DATA_" + keySuffix;
    }
}
